let Router = require("koa-router");
const multer = require("@koa/multer");
let router = new Router({ prefix: "/chat" });
const { SUCCESS_CODE, UPLOAD_PATH } = require("../utils/constant");
const { readmsg, getMessageList } = require("../service/chat");
const verifyAuth = require("../middleware/auth");
const storage = require("../utils/dest");
const upload = multer({ storage });
router.post("/readmsg", verifyAuth, async (ctx, next) => {
  const { from } = ctx.request.body;
  await readmsg(ctx, from)
    .then((res) => {
      ctx.response.body = {
        code: SUCCESS_CODE,
        message: "成功",
        data: res,
      };
    })
    .catch((err) => {
      ctx.app.emit("error", new Error(err), ctx);
    });
});

//查询聊天信息接口
router.get("/getmsglist", verifyAuth, async (ctx, next) => {
  const { _id } = ctx.query;
  await getMessageList(ctx, _id)
    .then((res) => {
      ctx.response.body = {
        code: SUCCESS_CODE,
        message: "查询成功",
        data: res,
      };
    })
    .catch((err) => {
      ctx.app.emit("error", new Error(err), ctx);
    });
});

router.post("/upload", verifyAuth, upload.single("resume"), (ctx) => {
  if (!ctx.file || ctx.file.length == 0) {
    ctx.app.emit("error", new Error("上传失败"), ctx);
  } else {
    console.log(ctx.file);
    ctx.response.body = {
      code: SUCCESS_CODE,
      message: "上传成功",
      data: ctx.file.filename,
    };
    console.log(ctx.response.body);
  }
});
module.exports = router;
